package aqsframework.selfmutex;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 豆包生成的自定义不可重入锁
 *
 *
 */
public class Mutex2 implements Lock {

    private static class Sync extends AbstractQueuedSynchronizer {
        @Override
        protected boolean tryAcquire(int acquires) {
            // 仅当状态为0时，表示没有被锁定，此时尝试获取锁
            if (compareAndSetState(0, 1)) {
                // 设置当前线程为持有锁的线程
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        @Override
        protected boolean tryRelease(int releases) {
            // 只有独占线程才能释放锁
            if (getState() == 0 || !isHeldExclusively()) {
                throw new IllegalMonitorStateException();
            }
            // 清除持有锁的线程
            setExclusiveOwnerThread(null);
            // 将状态设置为0
            setState(0);
            return true;
        }

        @Override
        protected boolean isHeldExclusively() {
            // 当状态为1时，表示锁被持有
            return getState() == 1;
        }

        Condition newCondition() {
            return new ConditionObject();
        }
    }



    private final Sync sync = new Sync();

    @Override
    public void lock() {
        // acquire是final的，不可以重写
        sync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        sync.release(1);
    }

    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }


    public static void main(String[] args) {
        Mutex2 lock = new Mutex2();
        new Thread(() -> {
            lock.lock();
            try {
                System.out.println("Thread 1 acquired the lock.");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }).start();

        new Thread(() -> {
            try {
                lock.lock();
                System.out.println("Thread 2 acquired the lock.");
            } finally {
                lock.unlock();
            }
        }).start();
    }


}
